package cn.neusoft.controller;


import cn.neusoft.domain.Order;
import cn.neusoft.domain.Task;
import cn.neusoft.exception.AppException;
import cn.neusoft.exception.AppExceptionCodeMsg;
import cn.neusoft.service.TaskService;
import cn.neusoft.vo.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Update;
import org.example.entity.DeliveryOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestController
@RequestMapping("/task")
@Api(value = "任务单模块API",description = "任务单相关功能")
public class TaskController {

    @Autowired
    TaskService taskService;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/num/{name}")
    public ResultBean findNum(@PathVariable("name") String name){
        String url = "http://localhost:8080/test/dispatch/getCargoQuaInWarehouse";
        Map<String, String> map = new HashMap<String, String>();
        map.put("warehouseName","东北库房");
        map.put("cargoDesName",name);
        return restTemplate.postForObject(url,map,ResultBean.class);
//          return ResultBean.success("查到库存了"+name);
    }


    @PostMapping("/date")
    public ResultBean findByDate(RequestDateBody requestDateBody){
        log.info(requestDateBody.toString());
        List<Task> re = taskService.findByDate(requestDateBody.startDate, requestDateBody.endDate);
        return ResultBean.success(re);
    }

    @GetMapping("/all")
    @ApiOperation(value = "查询所有的任务单")
    public ResultBean findAll(){
        List<Task> re= taskService.findAll();
        return ResultBean.success(re);
    }

    @PostMapping("/sgDd")
    @ApiOperation(value="手工调度后，修改对应任务单的信息")
    public ResultBean sgDiaodu(Task task) throws ParseException {
        if(task==null){
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        log.info("这是："+task.toString());
        //根据前端传过来的时间对任务单的完成时间进行设置（这个在手工调度需要用到）
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String nowdayTime = dateFormat.format(task.getServiceTime());
        Date nowDate = dateFormat.parse(nowdayTime);
        System.out.println(nowdayTime);
        task.setServiceTime(nowDate);
        task.setServiceCharge(taskService.getCharge(task.getFenzhanID()));
//        task.setFenzhanID(taskService.findFzid(teststr(task.getFenzhanID()).get(0).get("county")));
        taskService.sgDiaodu(task);
        return ResultBean.success();
    }



    @PostMapping
    @ApiOperation(value = "添加任务单")
    public ResultBean add(Task order) throws ParseException {
        if(order==null){
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        //设置随机任务单号
        order.setTaskID(new Order().getUUID());
        //根据商品名称获取Unit名称
        order.setUnit(taskService.getUnit(order.getProductName()));
        //根据邮寄的地址获取最近的分站的ID
        order.setFenzhanID(taskService.findFzid(teststr(order.getReceiverAddress()).get(0).get("county")));
        //根据所分配的分站设置所需要的邮寄费用
        order.setServiceCharge(taskService.getCharge(order.getFenzhanID()));
        //获取当前日期，并调取数据库中对应分站的预估运送时间，二者相加即为serviceTime:)
        Date d = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = dateFormat.format(d);
        Date now = dateFormat.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.DAY_OF_MONTH,taskService.getEctTime(order.getFenzhanID()));
        order.setServiceTime(dateFormat.parse(dateFormat.format(calendar.getTime())));
        //添加任务单
        taskService.add(order);
        return ResultBean.success();
    }

    @GetMapping("/id/{id}")
    @ApiOperation(value = "根据任务单号")
    public  ResultBean findById(@PathVariable("id") String id){
        if(id == ""){
//            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
            List<Task>re = taskService.findAll();
            return ResultBean.success(re);
        }
        List<Task>re = taskService.findByTaskId(id);
        return ResultBean.success(re);
    }

    @GetMapping("/postId/{id}")
    @ApiOperation(value = "根据任务单号")
    public  ResultBean findBypostID(@PathVariable("id") String id){
        if(id == ""){
//            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
            List<Task>re = taskService.findAll();
            return ResultBean.success(re);
        }
        List<Task>re = taskService.findBypostId(id);
        return ResultBean.success(re);
    }

    @GetMapping("/fenzhanId/{id}")
    @ApiOperation(value = "根据任务单号")
    public  ResultBean findByfenzhanId(@PathVariable("id") String id){
        if(id == ""){
//            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
            List<Task>re = taskService.findAll();
            return ResultBean.success(re);
        }
        List<Task>re = taskService.findByfenzhanId(id);
        return ResultBean.success(re);
    }

    @GetMapping("/rname/{name}")
    @ApiOperation(value = "根据任务单号")
    public  ResultBean findByrName(@PathVariable("name") String name){
        if(name == ""){
//            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
            List<Task>re = taskService.findAll();
            return ResultBean.success(re);
        }
        List<Task>re = taskService.findByrName(name);
        return ResultBean.success(re);
    }

    @GetMapping("/status/{id}")
    @ApiOperation(value = "根据任务单号")
    public  ResultBean findByStatus(@PathVariable("id") String id){
        if(id == ""){
//            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
            List<Task>re = taskService.findAll();
            return ResultBean.success(re);
        }
        List<Task>re = taskService.findByStatus(id);
        return ResultBean.success(re);
    }

    @GetMapping("/type/{id}")
    @ApiOperation(value = "根据任务单号")
    public  ResultBean findByType(@PathVariable("id") String id){
        if(id == ""){
//            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
            List<Task>re = taskService.findAll();
            return ResultBean.success(re);
        }
        List<Task>re = taskService.findByType(id);
        return ResultBean.success(re);
    }

    @PostMapping("/savetask/{taskId}/person/{personId}/fenzhanId/{fenzhanId}")
    public ResultBean allocate(@PathVariable String taskId, @PathVariable String personId, @PathVariable Long fenzhanId) {
        taskService.setPostman(taskId, personId);

        DeliveryOrder deliveryOrder = new DeliveryOrder();
        deliveryOrder.setTaskId(taskId);
        deliveryOrder.setDeliveryStatus("未开始");
        deliveryOrder.setDeliveryPersonId(personId);
        deliveryOrder.setSubstationId(fenzhanId);

        // 调用8088的添加deliveryOrderapi
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 设置请求体
        HttpEntity<DeliveryOrder> requestEntity = new HttpEntity<>(deliveryOrder, headers);

        // 发送POST请求
        String url = "http://localhost:8088/delivery-order/add"; // 注意URL的路径已经修改为被调用的API路径
        try {
            ResponseEntity<DeliveryOrder> responseEntity = restTemplate.postForEntity(url, requestEntity, DeliveryOrder.class);
            log.info("k");
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                DeliveryOrder addedDeliveryOrder = responseEntity.getBody();
                // 处理添加成功的情况
                return ResultBean.success("成功");
            } else {
                // 处理添加失败的情况
                return ResultBean.error();
            }
        } catch (Exception e) {
            // 处理任何其他异常
            log.error("出现异常", e);
            return ResultBean.error();
        }
    }




    @Data
    @NoArgsConstructor
    class RequestDateBody{
        String startDate;
        String endDate;
    }

    /**
     * 使用正则表达式匹配地址，并将地址字符串按省市区拆分用于找到最近的分站名称（少数民族地区也可用）
     * 对于直辖市（北京上海天津重庆）需要在区名前加“市辖区”否则无法匹配
     * @param address
     * @return
     */
    public List<Map<String,String>> teststr(String address) {
        String regex = "(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?<county>[^县]+县|.+区|.+市|.+旗|.+海域|.+岛)?(?<town>[^区]+区|.+镇)?(?<village>.*)";
        Matcher m = Pattern.compile(regex).matcher(address);
        String province = null, city = null, county = null, town = null, village = null;
        List<Map<String, String>> table = new ArrayList<Map<String, String>>();
        Map<String, String> row = null;
        while (m.find()) {
            row = new LinkedHashMap<String, String>();
            province = m.group("province");
            row.put("province", province == null ? "" : province.trim());
            city = m.group("city");
            row.put("city", city == null ? "" : city.trim());
            county = m.group("county");
            row.put("county", county == null ? "" : county.trim());
            town = m.group("town");
            row.put("town", town == null ? "" : town.trim());
            village = m.group("village");
            row.put("village", village == null ? "" : village.trim());
            table.add(row);
        }
        return table;
    }
    @Data
    public class Temp{
        int warehouseID;
        String cargoDesName;
    }
}
